//
//  CountryListDAO.m
//  ImGuider
//
//  Created by llt on 2017/4/24.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "CountryListDAO.h"
#import "DBHelper.h"

#define TABLE_NAME @"country_list"

#define ID      @"_id" // 本地数据库城市ID
#define JSON    @"JSON"
#define IDX     @"idx"

@implementation CountryListDAO

// 创建国家表
+ (BOOL)createMetadataTabWithDB:(FMDatabase *)db {
    
    if ([db tableExists:TABLE_NAME]) {
        [db executeUpdate:[NSString stringWithFormat:@"drop table %@",TABLE_NAME]];
    }
    
    NSString *sqlStr = [NSString stringWithFormat:@"create table %@(%@ integer not null primary key autoincrement,%@ text, %@ text)",TABLE_NAME,ID,IDX,JSON];
    BOOL success = [db executeUpdate:sqlStr];
    
    return success;
}

+ (Country *)getCountryWithRS:(FMResultSet *)set {
    
    NSString *json = [set stringForColumn:JSON];
    
    Country *country = [Country yy_modelWithJSON:json];
    country.localID = @([set intForColumn:ID]);
    
    return country;
}

+ (void)getCountryBlock:(void (^) (NSArray *keyArray,NSDictionary *countryDict))block {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        if ([db open]) {
            
            if (![db tableExists:TABLE_NAME]) {
                [self createMetadataTabWithDB:db];
                
            }
            
            NSString * sql = [NSString stringWithFormat:@"select * from %@ order by %@ asc",TABLE_NAME,IDX];
            FMResultSet *set = [db executeQuery:sql];
            
            NSMutableDictionary *cDict = [NSMutableDictionary dictionary];
            NSMutableArray *keyArray = [NSMutableArray array];
            
            
            BOOL needSort = NO;
            NSString *language = [AppManager sharedManager].language;
            
            if (![language hasPrefix:@"zh-Hans"] && ![language hasPrefix:@"zh-Hant"]) {
                needSort = YES;
            }
            
            while ([set next]) {
                
                Country *myCountry = [self getCountryWithRS:set];
                
                if (needSort) {
                    
                    if (myCountry.ename.length > 0) {
                        
                        NSString *idx = [myCountry.ename substringToIndex:1];
                        
                        if (idx.length > 0) {
                            myCountry.idx = [idx uppercaseStringWithLocale:[NSLocale currentLocale]];
                        }
                    }
                }
                
                NSMutableArray *cArray = cDict[myCountry.idx];
                
                if (!cArray) {
                    cArray = [NSMutableArray array];
                    [cDict setObject:cArray forKey:myCountry.idx];
                    [keyArray addObject:myCountry.idx];
                }
                
                [cArray addObject:myCountry];
                
            }
            
            
            if (needSort) {
                
                NSArray *sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
                    return [obj1 compare:obj2];
                }];
                
                NSMutableDictionary *sortDict = [NSMutableDictionary dictionary];
                
                [cDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSArray *obj, BOOL * _Nonnull stop) {
                    
                    NSArray *sortArray = [obj sortedArrayUsingComparator:^NSComparisonResult(Country *obj1, Country *obj2) {
                        return [obj1.ename compare:obj2.ename];
                    }];
                    
                    [sortDict setObject:sortArray forKey:key];
                    
                }];
                
                if (block) {
                    block(sortArray,sortDict);
                }
                
            } else {
                
                if (block) {
                    block(keyArray,cDict);
                }
            }
            [set close];
        }
        
    }];
}

+ (void)insertCountryArray:(NSArray *)countryArray success:(BOOL *)success {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        if ([db open]) {
            
            [self createMetadataTabWithDB:db];
            
            for (Country *country in countryArray) {
                
                NSString *json = [country yy_modelToJSONString];
                
                NSString *sql = [NSString stringWithFormat:@"insert into %@(%@,%@) values (?,?)",TABLE_NAME,IDX,JSON];
                
                *success = [db executeUpdate:sql,country.idx,json];
                
                if (!success) {
                    IGLog(@"----------------数据库插入错误-------------");
                    *rollback = YES;
                    return;
                }
                
            }
        }
        
    }];
}

@end
